package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eduplatform.common.JwtUtils;
import com.eduplatform.entity.User;
import com.eduplatform.mapper.UserMapper;
import com.eduplatform.service.BlacklistTokenService;
import com.eduplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private BlacklistTokenService blacklistTokenService;

    @Override
    public String login(String username, String password) {
        // Encrypt password
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        // Query user
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        queryWrapper.eq(User::getPassword, encryptedPassword);
        User user = this.getOne(queryWrapper);

        // If user exists, generate JWT token
        if (user != null) {
            return jwtUtils.generateToken(username);
        }

        return null;
    }

    @Override
    public boolean register(User user) {
        // Check if username already exists
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        if (this.count(queryWrapper) > 0) {
            return false;
        }

        // Encrypt password
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        // Set default values
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setIsDeleted(0);

        // Save user
        return this.save(user);
    }

    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        queryWrapper.eq(User::getIsDeleted, 0);
        return this.getOne(queryWrapper);
    }

    @Override
    public boolean logout(String token) {
        try {
            // 使用新的方法使token失效
            return jwtUtils.invalidateToken(token);

            // 旧的黑名单方法，保留注释以便参考
            /*
             * // 从token中获取过期时间
             * Date expireTime = jwtUtils.extractExpiration(token);
             * 
             * // 将token加入黑名单
             * return blacklistTokenService.addToBlacklist(token, expireTime);
             */
        } catch (Exception e) {
            return false;
        }
    }
}